#!/bin/bash

# 简单的IPK打包脚本
# 注意：这个脚本创建的是一个基本的IPK文件，可能不包含所有元数据

echo "Creating IPK package for luci-app-socatg..."

# 创建临时目录
TEMP_DIR="/tmp/luci-app-socatg-ipk"
rm -rf "$TEMP_DIR"  # 清理之前的构建
mkdir -p "$TEMP_DIR"
mkdir -p "$TEMP_DIR/usr/lib/lua/luci/controller"
mkdir -p "$TEMP_DIR/usr/lib/lua/luci/model/cbi"
mkdir -p "$TEMP_DIR/etc/config"
mkdir -p "$TEMP_DIR/etc/init.d"
mkdir -p "$TEMP_DIR/etc/uci-defaults"
mkdir -p "$TEMP_DIR/CONTROL"

# 复制文件
cp -r luasrc/controller/* "$TEMP_DIR/usr/lib/lua/luci/controller/"
cp -r luasrc/model/cbi/* "$TEMP_DIR/usr/lib/lua/luci/model/cbi/"
cp root/etc/config/socatg "$TEMP_DIR/etc/config/"
cp root/etc/init.d/socatg "$TEMP_DIR/etc/init.d/"
cp root/etc/uci-defaults/luci-socatg "$TEMP_DIR/etc/uci-defaults/"

# 创建control文件
cat > "$TEMP_DIR/CONTROL/control" << EOF
Package: luci-app-socatg
Version: 1.3-1
Depends: socat
Section: luci
Architecture: all
Maintainer: drophair <https://github.com/big-tooth>
Description: LuCI Support for socatg
 LuCI interface for socat port forwarding
 Supports multiple IPv6 to IPv4 port forwarding rules
EOF

# 创建postinst脚本
cat > "$TEMP_DIR/CONTROL/postinst" << EOF
#!/bin/sh

[ "\${IPKG_NO_SCRIPT}" = "1" ] && exit 0

[ "\$PKG_UPGRADE" = "1" ] || /etc/uci-defaults/luci-socatg

exit 0
EOF

# 创建prerm脚本
cat > "$TEMP_DIR/CONTROL/prerm" << EOF
#!/bin/sh

/etc/init.d/socatg stop

exit 0
EOF

# 添加执行权限
chmod +x "$TEMP_DIR/CONTROL/postinst"
chmod +x "$TEMP_DIR/CONTROL/prerm"
chmod +x "$TEMP_DIR/etc/init.d/socatg"
chmod +x "$TEMP_DIR/etc/uci-defaults/luci-socatg"

# 创建debian-binary文件
echo "2.0" > "$TEMP_DIR/debian-binary"

# 打包文件
cd "$TEMP_DIR"
tar -czf control.tar.gz CONTROL
find usr etc -type f -not -name "*.tar.gz" | xargs tar -czf data.tar.gz

# 创建release目录
RELEASE_DIR="/Users/wangzhuo/code/me/luci-app-socatg/release"
mkdir -p "$RELEASE_DIR"

# 创建IPK文件
OUTPUT_FILE="$RELEASE_DIR/luci-app-socatg_1.3-1_all.ipk"
rm -f "$OUTPUT_FILE"  # 删除之前的IPK文件

# 正确的IPK打包方式：三个文件需要在根目录
tar -czf "$OUTPUT_FILE" ./debian-binary ./control.tar.gz ./data.tar.gz

# 清理临时目录
rm -rf "$TEMP_DIR"

echo "IPK package created: $OUTPUT_FILE"

# 验证IPK文件
echo "Verifying IPK package..."
tar -tzf "$OUTPUT_FILE"